const logger = require('../config/logger');

// 响应时间中间件
const responseTime = (req, res, next) => {
  const startTime = process.hrtime.bigint();
  
  // 重写res.end方法来在响应发送前设置响应头
  const originalEnd = res.end;
  res.end = function(...args) {
    const endTime = process.hrtime.bigint();
    const responseTime = Number(endTime - startTime) / 1000000; // 转换为毫秒
    
    // 设置响应头（在响应发送前）
    if (!res.headersSent) {
      res.set('X-Response-Time', `${responseTime.toFixed(2)}ms`);
    }
    
    // 记录响应时间
    const logData = {
      requestId: req.requestId,
      method: req.method,
      url: req.originalUrl || req.url,
      statusCode: res.statusCode,
      responseTime: `${responseTime.toFixed(2)}ms`,
      ip: req.ip,
      userAgent: req.get('User-Agent'),
      userId: req.user?.id
    };
    
    // 根据响应时间选择日志级别
    if (responseTime > 5000) { // 超过5秒
      logger.error('Very Slow Response', logData);
    } else if (responseTime > 2000) { // 超过2秒
      logger.warn('Slow Response', logData);
    } else if (responseTime > 1000) { // 超过1秒
      logger.info('Response Time', logData);
    } else {
      logger.debug('Response Time', logData);
    }
    
    // 记录性能指标
    logger.performance(req.originalUrl || req.url, responseTime, {
      method: req.method,
      statusCode: res.statusCode,
      userId: req.user?.id
    });
    
    // 调用原始的end方法
    originalEnd.apply(this, args);
  };
  
  next();
};

module.exports = responseTime;